﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using LIMS.Shared;
using LIMS.Entities;
using System.Windows.Forms;

namespace LIMS.Windows
{

    public partial class ManufacturerManagement :LIMSPageBase<ManufacturersManagementPresenter>,IManufacturersPageView
    //public partial class UserManagement : Form
    {
       
        public ManufacturerManagement()
        {
            InitializeComponent();
        }

        private void ManufacturerManagement_Load(object sender, EventArgs e)
        {
            oGridData = null;
            //this.Presenter.InitializeView();
            GetManufacturerBasedOnCriteria(string.Empty);
            DisplayGrid();
            EnableDisableControls(false);
            btnDelete.Enabled = false;
            btnEdit.Enabled = false;
            GridPagingToolTip();
            bindStatus();
           
        }

        private void GridPagingToolTip()
        {
            System.Windows.Forms.ToolTip ToolTipText = new System.Windows.Forms.ToolTip();
            ToolTipText.SetToolTip(this.btnNext, "Next");
            ToolTipText.SetToolTip(this.btnFirst, "First");
            ToolTipText.SetToolTip(this.btnPrevious, "Previous");
            ToolTipText.SetToolTip(this.btnLast, "Last");
            ToolTipText.SetToolTip(this.btnSpecific, "Go to specific");
        }

        /// <summary>
        /// bindStatus
        /// </summary>
        private void bindStatus()
        {

            cmbStatus.DataSource = Resource.BindStatus();
            cmbStatus.DisplayMember = "StatusValue";
            cmbStatus.ValueMember = "StatusKey";
        }
        /// <summary>
        /// DisplayGrid
        /// </summary>
        private void DisplayGrid()
        {

            if (grdManufacturer.Columns[0].Displayed == false)
            {
                DataGridViewCheckBoxColumn oChkColumn = new DataGridViewCheckBoxColumn(false);

                oChkColumn.HeaderText = "Select";
                oChkColumn.Name = "Select";
                oChkColumn.Width = 50;

                grdManufacturer.Columns.Insert(0, oChkColumn);
            }

            grdManufacturer.MultiSelect = false;
            grdManufacturer.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grdManufacturer.AllowUserToAddRows = false;

            foreach (DataGridViewColumn dc in grdManufacturer.Columns)
            {
                if (dc.Index.Equals(0))
                {
                    dc.ReadOnly = false;
                }
                else
                {
                    dc.ReadOnly = true;
                }
            }
            grdManufacturer.RowHeadersVisible = false;
        }

        #region IUserManagementPageView Members

        private int iCurrentIndex;
        public int CurrentIndex
        {
            set
            {
                EnableDisableControls(true);
                iCurrentIndex = value;
                txtName.Text = oManufacturers[iCurrentIndex].Name;
                txtCode.Text = oManufacturers[iCurrentIndex].Code;
                txtContactName.Text = oManufacturers[iCurrentIndex].ContactName;
                txtEmail.Text = oManufacturers[iCurrentIndex].Email;
                txtContactName.Text=  oManufacturers[CurrentIndex].ContactName;
                txtCompanyName.Text = oManufacturers[CurrentIndex].CompanyName;
                txtTelephone.Text = oManufacturers[CurrentIndex].Telephone;
                txtVatNumber.Text = oManufacturers[CurrentIndex].VatNumber; 
                txtWebSite.Text = oManufacturers[CurrentIndex].Website ;
                txtAddress.Text = oManufacturers[CurrentIndex].Address;
                cmbStatus.SelectedValue = Manufacturers[iCurrentIndex].Status;            
            }
            get
            {
                return iCurrentIndex;
            }
        }

        public void FillPageData()
        {
          
        }

        private GridViewData oGridData;
        public GridViewData GridData
        {
            set
            {
                oGridData = value;
                lblTotal.Text = "/ " + (value.TotalRecords / value.PageSize + ((value.TotalRecords % value.PageSize > 0) ? 1 : 0)).ToString();
                txtPageNo.Text = value.PageIndex.ToString();
            }
            get
            {
                if (oGridData != null)
                {
                    return oGridData;
                }
                else
                {
                    GridViewData grdData = new GridViewData();
                    grdData.SortOrder = "ASC";
                    grdData.SortColumn = "CreatedDateTime";
                    grdData.PageSize = 2;//SetGridPageSize();
                    grdData.PageIndex = 1;
                    return grdData;
                }

            }
        }

        public void ShowMessage(MessageType type, string sMessage)
        {
            //throw new NotImplementedException();
        }

        private List<Manufacturers> oManufacturers;
        public List<Manufacturers> Manufacturers
        {
            get
            {
                if (oManufacturers == null)
                {
                    oManufacturers = new List<Manufacturers>();
                }
                return oManufacturers;
            }
            set
            {
                oManufacturers = value;
                grdManufacturer.DataSource = ConvertListToDataTable(oManufacturers);
                grdManufacturer.Columns[0].Visible = false;
            }
        }

        #endregion

        private DataTable ConvertListToDataTable(List<Manufacturers> list)
        {
            // New table.
            DataTable table = new DataTable();
            DataColumn oColumn0 = new DataColumn("Id", typeof(int));
            DataColumn oColumn1 = new DataColumn("Name", typeof(string));
            DataColumn oColumn2 = new DataColumn("Code", typeof(string));
            DataColumn oColumn3 = new DataColumn("Contact Name", typeof(string));
            DataColumn oColumn4 = new DataColumn("Email", typeof(string));
            //DataColumn oColumn5 = new DataColumn("Email", typeof(string));
            table.Columns.Add(oColumn0);
            table.Columns.Add(oColumn1);
            table.Columns.Add(oColumn2);
            table.Columns.Add(oColumn3);
            table.Columns.Add(oColumn4);

            for (int i = 0; i < list.Count; i++)
            {
                DataRow oNewRow = table.NewRow();
                oNewRow["Id"] = list[i].Id;
                oNewRow["Name"] = list[i].Name;
                oNewRow["Code"] = list[i].Code;
                oNewRow["Contact Name"] = list[i].ContactName;
                oNewRow["Email"] = list[i].Email;

                table.Rows.Add(oNewRow);
            }
            return table;
        }

        private void btnSaveManufacturer_Click(object sender, EventArgs e)
        {
            if (Validations.IsEmpty(txtName.Text.Trim()) || Validations.IsEmpty(txtCode.Text.Trim()) ||
                Validations.IsEmpty(txtEmail.Text.Trim()) || Validations.IsEmpty(txtCompanyName.Text.Trim()) ||
                Validations.IsEmpty(txtAddress.Text.Trim()) || Validations.IsEmpty(txtContactName.Text.Trim()) ||
                Validations.IsEmpty(txtTelephone.Text.Trim()) || Validations.IsEmpty(txtVatNumber.Text.Trim()) ||
                Validations.IsEmpty(txtWebSite.Text.Trim())  ||   Validations.IsCmbboxDefaultValue((cmbStatus.SelectedValue).ToString()))
            {
                MessageBox.Show("Fill mandatory(*) information.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                oManufacturers[CurrentIndex].Name = txtName.Text;
                oManufacturers[CurrentIndex].Code = txtCode.Text;
                oManufacturers[CurrentIndex].Email = txtEmail.Text;
                oManufacturers[CurrentIndex].ContactName = txtContactName.Text;
                oManufacturers[CurrentIndex].CompanyName = txtCompanyName.Text;   
                oManufacturers[CurrentIndex].Telephone = txtTelephone.Text;
                oManufacturers [CurrentIndex].VatNumber= txtVatNumber.Text;
                oManufacturers[CurrentIndex].Website = txtWebSite.Text;
                oManufacturers[CurrentIndex].Address = txtAddress.Text;
                oManufacturers[CurrentIndex].CreatedBy = 1; /// logged in user
                oManufacturers[CurrentIndex].CreatedDateTime = DateTime.Now;
                oManufacturers[CurrentIndex].Status = Convert.ToString(cmbStatus.SelectedValue);
               
                if (this.Presenter.Save(oManufacturers[CurrentIndex]))
                {
                    MessageBox.Show(Resource.MANUFACTURER_SAVED_SUCCESSFULLY);
                    EnableDisableControls(false);
                    ClearData();
                }

                this.Presenter.InitializeView();
                DisplayGrid();
                btnEdit.Enabled = false;
                btnDelete.Enabled = false;
            }
        }

        private void ClearData()
        {

            txtName.Text = String.Empty;
            txtCode.Text = String.Empty;
            txtEmail.Text = String.Empty;
            txtContactName.Text = String.Empty;
            txtCompanyName.Text = String.Empty;       
            txtAddress.Text = String.Empty;
            txtWebSite.Text = String.Empty;
            txtVatNumber.Text = String.Empty;
            txtTelephone.Text = String.Empty;         
            
            //lstDepartment.SelectedValue = 0;
            cmbStatus.SelectedValue = "X";
        }
        /// <summary>
        /// grdUser_CellContentClick
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdManufacturer_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            bool bChkBoxSelected = false;
            int iManufcaturerID = Convert.ToInt32(grdManufacturer.Rows[grdManufacturer.CurrentRow.Index].Cells["Id"].Value);
            m_iManufcaturerId = iManufcaturerID;

            for (int iRowCount = 0; iRowCount < grdManufacturer.Rows.Count; iRowCount++)
            {
                DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdManufacturer.Rows[iRowCount].Cells[0];
                if (cell is DataGridViewCheckBoxCell)
                {
                    if ((bool)cell.EditedFormattedValue)
                    {
                        bChkBoxSelected = true;
                        break;
                    }
                }
            }
            if (bChkBoxSelected)
            {
                btnDelete.Enabled = true;
                btnEdit.Enabled = true;
            }
            else
            {
                btnDelete.Enabled = false;
                btnEdit.Enabled = false;
            }
        }

        private static int m_iManufcaturerId = 0;
        /// <summary>
        /// btnEdit_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (m_iManufcaturerId > 0)
            {
                int iSelectedRowsCount = 0;
                int iRowIndex = 0;
                for (int iRowCount = 0; iRowCount < grdManufacturer.Rows.Count; iRowCount++)
                {
                    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdManufacturer.Rows[iRowCount].Cells[0];
                    if (cell is DataGridViewCheckBoxCell)
                    {
                        if ((bool)cell.EditedFormattedValue)
                        {
                            iRowIndex = iRowCount;
                            iSelectedRowsCount++;
                        }
                    }
                }
                if (iSelectedRowsCount > 1)
                {
                    MessageBox.Show("Select single row to edit the record.");
                    return;
                }
                else if (iSelectedRowsCount == 0)
                {
                    MessageBox.Show("Select atleast one record to edit.");
                    return;
                }

                /// Edit
                btnSave.Enabled = true;
                CurrentIndex = iRowIndex;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (m_iManufcaturerId > 0)
            {
                int iSelectedRowsCount = 0;
                for (int iRowCount = 0; iRowCount < grdManufacturer.Rows.Count; iRowCount++)
                {
                    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdManufacturer.Rows[iRowCount].Cells[0];
                    if (cell is DataGridViewCheckBoxCell)
                    {
                        if ((bool)cell.EditedFormattedValue)
                        {
                            iSelectedRowsCount++;
                        }
                    }
                }
                if (iSelectedRowsCount == 0)
                {
                    MessageBox.Show("Select atleast one record to delete.");
                    return;
                }

                DialogResult oResult = MessageBox.Show("Are you sure to delete the selected records?", "Delete user", MessageBoxButtons.YesNo);
                if (oResult.Equals(DialogResult.Yes))
                {
                    /// Delete
                    for (int iRowCount = 0; iRowCount < grdManufacturer.Rows.Count; iRowCount++)
                    {
                        DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdManufacturer.Rows[iRowCount].Cells[0];
                        if (cell is DataGridViewCheckBoxCell)
                        {
                            if ((bool)cell.EditedFormattedValue)
                            {
                                this.Presenter.Delete(oManufacturers[iRowCount]);
                            }
                        }
                    }
                    this.Presenter.InitializeView();
                    DisplayGrid();
                    
                    ClearData();
                    EnableDisableControls(false);
                    btnEdit.Enabled = false;
                    btnDelete.Enabled = false;
                }

            }
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            try
            {
                GridData.PageIndex = 1;//(GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0) -1 );
                GetManufacturerBasedOnCriteria(string.Empty);

            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

      
        private void GetManufacturerBasedOnCriteria(string p_sCriteria)
        {
            try
            {
                if (txtSearch.Text.Trim().Length == 0)
                {
                    this.Presenter.InitializeView();
                }
                else
                {
                    this.Presenter.SearchManufacturerByKeyword(p_sCriteria);
                }
                DisplayGrid();
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            try
            {
                if (GridData.PageIndex > 1)
                {
                    GridData.PageIndex--;
                    GetManufacturerBasedOnCriteria(string.Empty);

                }
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }

        }


        private void btnLast_Click(object sender, EventArgs e)
        {
            try
            {
                GridData.PageIndex = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0));
                GetManufacturerBasedOnCriteria(string.Empty);

            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void btnSpecific_Click(object sender, EventArgs e)
        {
            try
            {
                int userCurrentPage = 0;

                if (!int.TryParse(txtPageNo.Text, out userCurrentPage))
                {
                    userCurrentPage = 1;
                }

                int maxPageSize = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0));
                if (userCurrentPage > maxPageSize)
                {
                    userCurrentPage = 1;
                }
                GridData.PageIndex = userCurrentPage;
                GetManufacturerBasedOnCriteria(string.Empty);

            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                int maxPageSize = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0) - 1);

                if (GridData.PageIndex <= maxPageSize)
                {
                    GridData.PageIndex++;
                    GetManufacturerBasedOnCriteria(string.Empty);
                }
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void btnAddNewManufacturer_Click(object sender, EventArgs e)
        {
            EnableDisableControls(true);
            cmbStatus.SelectedValue = "X";
            txtName.Focus();
            Manufacturers  newManufacturer = new Manufacturers ();
            oManufacturers.Add(newManufacturer);
            CurrentIndex = oManufacturers.Count - 1;
            cmbStatus.SelectedIndex = 0;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string sCriteria = txtSearch.Text.Trim();
            if (sCriteria.Length > 0)
            {
                if (sCriteria.Contains("*"))
                {
                    if (sCriteria.Equals("*"))
                    {
                        sCriteria = string.Empty;
                    }
                    else
                    {
                        sCriteria = sCriteria.Replace("*", "%");
                    }
                }
                else if (sCriteria.Contains("?"))
                {
                    sCriteria = sCriteria.Replace("?", "%");
                }
            }
            GetManufacturerBasedOnCriteria(sCriteria);

        }

        /// <summary>
        /// Enable disable form controls on action basis.
        /// if bValue is true contrlos will be enabled else disabled.
        /// </summary>
        /// <param name="bValue"></param>
        private void EnableDisableControls(bool bValue)
        {
            try
            {
                txtName.Enabled = bValue;
                txtCode.Enabled = bValue;
                txtEmail.Enabled = bValue;
                txtContactName.Enabled = bValue;
                txtCompanyName.Enabled = bValue;
                txtAddress.Enabled = bValue;
                txtWebSite.Enabled = bValue;
                txtVatNumber.Enabled = bValue;
                txtTelephone.Enabled = bValue;            
                cmbStatus.Enabled = bValue;
                btnSave.Enabled = bValue;
                btnClear.Enabled = bValue;
            }
            catch (Exception ex)
            { 
            }
        }

    

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearData();
        }
    }
}
